<?php
namespace Pub\wx;
defined('IN_IA') or exit('Access Denied');
use Pub\tool\Tool;

class WxTpl extends Wx
{
    private $_tpls = array(
        "message_media_check"=>"OPENTM407317566",
        "message_media_pass"=>"OPENTM411453653"
    );

    public function __construct()
    {
        parent::__construct();
    }

    /**
     * 获取公众号行业
     */
    public function getIndustry()
    {
        $_industry = $this->wxHttpsRequestPem("https://api.weixin.qq.com/cgi-bin/template/get_industry?access_token=".$this->getAccessToken());
        return $_industry;
    }

    /**
     * 设置模板消息行业
     * @return array
     */
    public function setIndustry()
    {
        $_data = array("industry_id1"=>1,"industry_id2"=>2);
        $_data = json_encode($_data);
        $_result = $this->wxHttpsRequestPem("https://api.weixin.qq.com/cgi-bin/template/api_set_industry?access_token=".$this->getAccessToken(),$_data);
        return $_result;
    }

    /**
     * 获取模板消息id
     */
    public function get()
    {
        $_data = array();
        foreach($this->_tpls as $_k=>$_v){
            $_data_data = array("template_id_short"=>$_v);
            $_data_data = json_encode($_data_data);
            $_tpl = $this->wxHttpsRequestPem("https://api.weixin.qq.com/cgi-bin/template/api_add_template?access_token=".$this->getAccessToken(),$_data_data);
            $_tpl = json_decode($_tpl,true);
            if($_tpl["errmsg"] == "ok"){
                $_data[$_k] = $_tpl['template_id'];
            }else{
                return array("status"=>"error","data"=>$_tpl);
            }
        }
        return array("status"=>"success","data"=>$_data);
    }

    /**
     * 删除模板消息ID
     * @param array $_data 模板消息数据
     */
    public function remove($_data)
    {
        foreach($_data as $_v){
            $_data_data = array("template_id"=>$_v);
            $_data_data = json_encode($_data_data);
            $this->wxHttpsRequestPem("https://api.weixin.qq.com/cgi-bin/template/del_private_template?access_token=".$this->getAccessToken(),$_data_data);
        }
    }

    /**
     * 发送模板消息
     */
    public function send($_openid,$_tpl_id,$_data,$_url = "")
    {
        $_send_data = array(
            "touser"=>$_openid,
            "template_id"=>$_tpl_id,
            "url"=>$_url,
            "data"=>$_data
        );
        $_send_data = json_encode($_send_data);
        $_result = $this->wxHttpsRequestPem("https://api.weixin.qq.com/cgi-bin/message/template/send?access_token=".$this->getAccessToken(),$_send_data);
        return $_result;
    }
}